package com.hzncc.scaffold.controller.Rear.User;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Other.User;
import com.hzncc.scaffold.entity.Vo.ManageResetPwdVo;
import com.hzncc.scaffold.entity.Vo.MyInfoVo;
import com.hzncc.scaffold.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: DrunkBear
 * @Date: 2022-05-25 16:26
 * @Description: null
 */
@Api(tags = "后台用户管理-我的")
@RequestMapping("/manage/user")
@RestController
public class MyController {

    @Autowired
    UserService userService;

    @GetMapping("/myInfo")
    @ApiOperation("我的信息")
    public ResultT myInfo(){

        long loginIdAsInt = StpUtil.getLoginIdAsInt();
        if(userService.getById(loginIdAsInt)==null){
            return ResultT.fail("数据错误");
        }
            User user = userService.getById(loginIdAsInt);
            MyInfoVo myInfoVo = BeanUtil.toBean(user, MyInfoVo.class);
            return ResultT.success(myInfoVo);
    }

    @PostMapping("/resetPwd")
    @ApiOperation("重置密码")
    public ResultT resetPwd(@RequestBody ManageResetPwdVo manageResetPwdVo){

        String pwd = manageResetPwdVo.getPwd();
        String newPwd = manageResetPwdVo.getNewPwd();
        String confirmpass = manageResetPwdVo.getConfirmpass();

        if(!newPwd.equals(confirmpass)){
            return ResultT.fail("两次输入密码不一致");
        }

        int loginIdAsInt = StpUtil.getLoginIdAsInt();

        if(userService.getById(loginIdAsInt)==null){
            return ResultT.fail("数据错误");
        }

        User user = userService.getById(loginIdAsInt);

        if(BCrypt.checkpw(pwd,user.getPassword())){
            String gensalt = BCrypt.gensalt();
            String hashpw = BCrypt.hashpw(newPwd, gensalt);

            user.setPassword(hashpw);
            boolean update = userService.updateById(user);

            if(update){
               return ResultT.success("操作成功");
            }else {
                return ResultT.fail("操作失败");
            }
        }else {
            return ResultT.fail("账号密码错误");
        }
    }
}
